package com.program.facesigninsystem.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author Mapler
 */
@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String from;

    private JavaMailSender mailSender;

    @Autowired
    public MailService(JavaMailSender javaMailSender) {
        this.mailSender = javaMailSender;
    }

    /**
     * 简单文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String content){

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        mailSender.send(message);
    }

    /**
     * 发送带图片的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscId
     * @throws MessagingException
     */
    @Async
    public void sendInlineResourceMail(String to, String subject, String content, File file, String rscId) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource res = new FileSystemResource(file);
        helper.addInline(rscId, res);
        mailSender.send(message);
    }

}
